"""
开机自启动管理模块
Windows平台通过注册表实现开机自启动
"""
import os
import sys
import winreg


class StartupManager:
    """开机自启动管理器"""
    
    APP_NAME = "LAN对讲机"
    
    @staticmethod
    def get_executable_path():
        """获取可执行文件路径"""
        if getattr(sys, 'frozen', False):
            # 打包后的exe
            return sys.executable
        else:
            # 开发环境
            return os.path.abspath(sys.argv[0])
    
    @staticmethod
    def is_startup_enabled():
        """检查是否已启用开机自启动"""
        try:
            key = winreg.OpenKey(
                winreg.HKEY_CURRENT_USER,
                r"Software\Microsoft\Windows\CurrentVersion\Run",
                0,
                winreg.KEY_READ
            )
            try:
                winreg.QueryValueEx(key, StartupManager.APP_NAME)
                winreg.CloseKey(key)
                return True
            except FileNotFoundError:
                winreg.CloseKey(key)
                return False
        except Exception as e:
            print(f"检查启动项失败: {e}")
            return False
    
    @staticmethod
    def enable_startup():
        """启用开机自启动"""
        try:
            key = winreg.OpenKey(
                winreg.HKEY_CURRENT_USER,
                r"Software\Microsoft\Windows\CurrentVersion\Run",
                0,
                winreg.KEY_WRITE
            )
            exe_path = StartupManager.get_executable_path()
            # 添加 --autostart 参数以标识是开机自动启动
            winreg.SetValueEx(key, StartupManager.APP_NAME, 0, winreg.REG_SZ, f'"{exe_path}" --autostart')
            winreg.CloseKey(key)
            return True
        except Exception as e:
            print(f"启用开机自启动失败: {e}")
            return False
    
    @staticmethod
    def disable_startup():
        """禁用开机自启动"""
        try:
            key = winreg.OpenKey(
                winreg.HKEY_CURRENT_USER,
                r"Software\Microsoft\Windows\CurrentVersion\Run",
                0,
                winreg.KEY_WRITE
            )
            try:
                winreg.DeleteValue(key, StartupManager.APP_NAME)
            except FileNotFoundError:
                pass
            winreg.CloseKey(key)
            return True
        except Exception as e:
            print(f"禁用开机自启动失败: {e}")
            return False

